package com.zktravel.core.bean;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.springframework.util.Assert;

import com.google.common.collect.Lists;
import com.odianyun.util.db.query.QueryParam;
import com.odianyun.util.db.query.Sort;
import com.odianyun.util.reflect.ReflectUtils;

/**
 * Created by wubo- on 2017/8/30.
 */
public class RemoteQueryArgs extends QueryArgs {
    private String[] selectFields;
    private Page page;

    public void setSelectFields(String[] selectFields) {
		this.selectFields = selectFields;
	}
	public String[] getSelectFields() {
        return selectFields;
    }
    public RemoteQueryArgs withSelectFields(String... selectFields) {
        this.selectFields = selectFields;
        return this;
    }
	public IPage getPage() {
		return page;
	}
	public void setPage(Page page) {
		this.page = page;
	}
    public RemoteQueryArgs withPage(Page page) {
        this.page = page;
        return this;
    }
    
	public final void checkSelectFields(Class<?> voClass) {
		if (selectFields == null) return;
		
        Field[] fields = ReflectUtils.getDeclaredFields(voClass, null, true, false);
        
        List<String> fieldList = Lists.newArrayListWithExpectedSize(fields.length);
        for (Field f : fields) {
        	if (f.getType().isArray()) {
        		continue;
        	}
        	if (Collection.class.isAssignableFrom(f.getType())) {
        		continue;
        	}
        	fieldList.add(f.getName());
        }
        
        if (! fieldList.containsAll(Arrays.asList(selectFields))) {
            throw new IllegalArgumentException("Select fields is illegal");
        }
    }
    
    public final void checkFilterFields(String... fields) {
    	if (getFilters().isEmpty()) return;
    	
    	Assert.notEmpty(fields, "Parameter fields is required");
    	
    	List<String> fieldList = Arrays.asList(fields);
    	if (! fieldList.containsAll(getFilters().keySet())) {
            throw new IllegalArgumentException("Filter fields is illegal");
    	}
    }
    
    public final void checkSortFields(String... fields) {
    	List<Sort> sorts = getSorts();
    	if (sorts == null || sorts.isEmpty()) return;
    	
    	Assert.notEmpty(fields, "Parameter fields is required");
    	
    	List<String> fieldList = Arrays.asList(fields);
    	
		for (Sort sort : sorts) {
			if (! fieldList.contains(sort.getField())) {
                throw new IllegalArgumentException("Sort field "+sort.getField()+" is illegal");
			}
		}
    }
    
    public QueryParam toQueryParam(Class<?> voClass, String...includeKeys) {
    	QueryParam q = super.getConvertor(includeKeys).toQueryParam();
        if (selectFields != null) {
            q.includeSelectFields(selectFields);
        }
        checkSelectFields(voClass);
        
        return q;
    }
   
}
